package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@RestController
public class AilPayController {
    @Value("${alipay.appid}")
    private String APP_ID;
    @Value("${alipay.app_private_key}")
    private String APP_PRIVATE_KEY;
    @Value("${alipay.alipay_public_key}")
    private String ALIPAY_PUBLIC_KEY;
    @Value("${alipay.url}")
    private String url;

    @RequestMapping("/pay")
    public   String   doPost (@RequestBody Map map, HttpServletRequest httpRequest, HttpServletResponse httpResponse)   throws ServletException, IOException {
        UUID uuid = UUID.randomUUID();
        String string = uuid.toString();
        String replace = string.replace("-", "");
        Object price = map.get("price");
        Double money = Double.valueOf(price.toString());

        AlipayClient alipayClient =  new  DefaultAlipayClient( url , APP_ID, APP_PRIVATE_KEY, "json", "utf-8", ALIPAY_PUBLIC_KEY, "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        //同步返回的调用结果,通常返回到商品的支付页面
        alipayRequest.setReturnUrl( "http://gxyv7j.natappfree.cc/#/order" );
        //异步返回的结果 ---》当用户支付成功后，支付宝通过post请求到了你的接口的地址，将支付的参数携带，并且用户进行验签
        alipayRequest.setNotifyUrl( "http://8sxc3r.natappfree.cc/notifyUrl" ); //在公共参数中设置回跳和通知地址

        //使用FastJson进行转换
        Map maps = new HashMap();
        maps.put("out_trade_no",replace);
        maps.put("product_code","FAST_INSTANT_TRADE_PAY");
        maps.put("total_amount",money);
        maps.put("subject","半次元订单");
        maps.put("body","手办");
        String string1 = JSONObject.toJSONString(maps);
        alipayRequest.setBizContent(string1);

//        alipayRequest.setBizContent( "{"  +
//                "    \"out_trade_no\":\"201503200101010011\","  +
//                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
//                "    \"total_amount\":88.88,"  +
//                "    \"subject\":\"Iphone6 16G\","  +
//                "    \"body\":\"Iphone6 16G\","  +
//                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","  +
//                "    \"extend_params\":{"  +
//                "    \"sys_service_provider_id\":\"2088511833207846\""  +
//                "    }" +
//                "  }" ); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
//          httpResponse.setContentType( "text/html;charset=utf-8");
//          httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
//           httpResponse.getWriter().flush();
//           httpResponse.getWriter().close();
        return form;
    }

    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException {
        Map<String, String> paramsMap = convertRequestParamsToMap(request); //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2"); //调用SDK验证签名
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println("支付成功");

        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }


}
